<?php

namespace App\Http\Controllers\Home;

use App\Models\Activitys;
use App\Models\Areas;
use App\Models\BidLists;
use App\Models\Cases;
use App\Models\Categorys;
use App\Models\Collections;
use App\Models\Footprints;
use App\Models\Orders;
use App\Models\Phonemap;
use App\Models\Services;
use App\Models\SignUps;
use App\Models\StoreEvaluates;
use App\Models\Stores;
use App\Models\UserInfos;
use App\Models\Users;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class StoreController extends Controller
{
    /**
     * 供应商列表页面
     * @param url home.store.storeList
     * @param Request $request
     * @param store_id 当前供应商id
     * @param store_name 当前供应商名称
     * @param content 评价内容
     * @param speed 工作速度评分
     * @param quality 工作质量评分
     * @param attitude 工作态度评分
     * @return bool
     */
    public function storeList(Request $request){
        $title = '供应商列表';
        return view('home.store.storeList',compact('title'));
    }

    /**
     * 供应商列表
     * @param url home.store.lists
     * @param Request $request
     * @param cid 一级分类id
     * @param keyword 热搜词条
     * @param cid_id 二级分类id
     * @param area 区域id
     * @param recommend 推荐 2:官网推荐 不传或其他：无要求
     * @param sid 排序id 1:致电量 2:浏览量 3:点赞量 4:成交量 不传或其他值：创建时间
     * @param orderby 'desc'倒叙 'asc'正序
     * @return bool
     */
    public function listsApi(Request $request)
    {
        try{
            $map = [
                'keyword' => (string)$request->get('keyword'),//热搜词条
                'cid' => (int)$request->get('cid'),//一级分类id
                'cid_id' => (int)$request->get('cid_id'),//二级分类id
                'service_area' => $request->get('area'),
                'pc_recomment' => (int)$request->get('recommend'),
            ];

            $page = (int)$request->get('page',1);//页码
            $sid = (int)$request->get('sid');//排序
            $orderby = (string)$request->get('orderby','desc');//排序
            if ($sid == 1){
                $sort = 'call';
            }elseif ($sid == 2){
                $sort = 'view';
            }elseif ($sid == 3){
                $sort = 'credit';
            }elseif ($sid == 4){
                $sort = 'service';
            }else{
                $sort = 'created_at';
            }
            $lists = [];
            $lists['cate_id'] = Categorys::getcates(['pid'=>0],['id','name','pid']);//一级分类
            $fields = ['id','user_id','store_name','logo','cate_id','description','call','view','service','credit','service_scope','hot','quality'];
            //二级分类
            if(empty($map['cid'])){
                $cate_ids = Categorys::where('pid',0)->where('status','<>',-1)->orderBy('sort','asc')->pluck('id')->toArray();
                $field = " field(pid,".implode(',',$cate_ids)."),sort";
                $lists['children'] = Categorys::whereIn('pid',$cate_ids)->orderByRaw($field)->get(['id','name','pid'])->toArray();
//                $lists['children'] = Categorys::where('pid','<>','0')->orderBy('sort','asc')->get(['id','name','pid'])->toArray();
            }else{
                $lists['children'] = Categorys::getcates(['pid'=>$map['cid']],['id','name','pid'])->toArray();
            }
            $lists['store'] = Stores::allLists($map, $fields, $page, 10, $sort, $orderby);
            foreach ($lists['store'] as $key=>$val){
                $lists['store'][$key]['bool'] = false;
                $lists['store'][$key]['link'] = ['master_name'=>'','master_phone'=>''];
                $lists['store'][$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
                $lists['store'][$key]['call'] = strlen($val['call'])>=4 ? '999+' : $val['call'];
                $lists['store'][$key]['service'] = strlen($val['service'])>=4 ? '999+' : $val['service'];
                //擅长领域
                if (!empty($val['cate_id'])){
                    $cate_id = explode(',',$val['cate_id']);
                    foreach ($cate_id as $kk => $vv){
                        $pidTree[] = Categorys::where(['id'=>$vv])->first('name');
                    }
                }else{
                    $pidTree['name'] = [];
                }
                $lists['store'][$key]['cate_name'] = $pidTree;
                $pidTree = [];
            }
            $lists['area'] = Areas::where('status','<>',-1)->orderBy('sort','asc')->get(['id','name','pid']);//服务区域
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 右侧供应商
     * @param url home.store.rightStoreApi
     * @return bool
     */
    public function rightStoreApi()
    {
        try{
            $fields = ['id','user_id','store_name','logo','cate_id','description','call','view','service','credit','service_scope','hot','quality','credit'];
            $lists = Stores::allLists(['recommend'=>2],$fields, null, 3 );
            foreach ($lists as $key=>$val){
                $lists[$key]['link'] = ['master_name'=>'','master_phone'=>''];
                $lists[$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
                $lists[$key]['call'] = strlen($val['call'])>=4 ? '999+' : $val['call'];
                $lists[$key]['service'] = strlen($val['service'])>=4 ? '999+' : $val['service'];
                $lists[$key]['bool'] = false;
                //擅长领域
                if (!empty($val['cate_id'])){
                    $cate_id = explode(',',$val['cate_id']);
                    foreach ($cate_id as $kk => $vv){
                        $pidTree[] = Categorys::where(['id'=>$vv])->first('name');
                    }
                }else{
                    $pidTree['name'] = [];
                }
                $lists[$key]['cate_name'] = $pidTree;
            }
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 供应商首页
     * @param url home.store.store
     * @param Request $request
     * @return bool
     */
    public function store(){
        $title = '供应商首页';
        return view('home.store.store',compact('title'));
    }

    /**
     * 供应商基本详情
     * @param url home.store.storeDetails
     * @param Request $request
     * @param id 供应商id
     * @return bool
     * @return is_collect 1:未收藏 2:已收藏
     */
    public function storeDetailsApi(Request $request){
        try{
            $id = (int)$request->get('id');//供应商id
            if (empty($id)) return $this->writeJson(1,null,'参数错误');
            $fields = ['id','store_name','logo','banner','seller_name','cate_id','call','credit','collections','hot','quality','workingtime','area_info','description','view'];
            $lists = Stores::details(['id'=>$id], $fields);
            $lists['link'] = ['master_name'=>'','master_phone'=>''];
            $lists['bool'] = false;
            $lists['call'] = strlen($lists['call'])>=4 ? '999+' : $lists['call'];
            $lists['view'] = strlen($lists['view'])>=4 ? '999+' : $lists['view'];
            //擅长领域
            if (!empty($lists['cate_id'])){
                $lists['cate_id'] = explode(',',$lists['cate_id']);
                foreach ($lists['cate_id'] as $k => $v){
                    $pidTree[] = Categorys::where('id',$v)->first('name');
                }
            }else{
                $pidTree['name'] = [];
            }

            $lists['cate_id'] = $pidTree;
            //判断是否收藏
            $lists['is_collect'] = 1;//默认未收藏
            $userinfo = auth()->guard('web')->user();//获取当前登录用户
            if (!empty($userinfo)){
                if ($userinfo['type'] == 1){
                    $collect = Collections::where(['collect_id'=>$id,'user_id'=>$userinfo['id'],'type'=>4])->value('collect_id');
                    $lists['is_collect'] = empty($collect) ? 1 : 2;
                }
                //添加足迹
                $foot_arr = [
                    'user_id' => $userinfo['id'],
                    'foot_id' => $id,
                    'type'    => 1,
                ];
                $foot_id = Footprints::where($foot_arr)->value('id');
                if($foot_id > 0){
                    Footprints::where($foot_arr)->update(['updated_at'=>date('Y-m-d H:i:s')]);
                }else{
                    Footprints::create($foot_arr);
                }
            }
            Stores::where('id',$id)->increment('view');//浏览量加1
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 供应商预览
     * @param Request $request
     * @return bool
     */
    public function storePrev(){
        $title = '供应商预览';
        return view('home.store.storeprev',compact('title'));
    }

    /**
     * 供应商基本详情预览
     * @param url home.store.storeDetails
     * @param Request $request
     * @param store_id 供应商id
     * @param user_id 供应商用户id
     */
    public function storePrevApi(Request $request){
        try{
            $store_id = (int)$request->post('store_id');//供应商id
            $seller_id = (int)$request->post('user_id');//供应商id//当前店铺主人id
            if (empty($store_id) || empty($seller_id)) return $this->writeJson(1,null,'参数错误');

            $fields = ['id','store_name','logo','banner','seller_name','cate_id','call','credit','collections','hot','quality','workingtime','area_info','description'];
            $lists = Stores::details(['id'=>$store_id,'user_id'=>$seller_id], $fields);
            if(!$lists){
                return $this->writeJson(1,null,'当前用户的店铺不存在');
            }
            $lists['link'] = ['master_name'=>'','master_phone'=>''];
            $lists['bool'] = false;
            $lists['call'] = strlen($lists['call'])>=4 ? '999+' : $lists['call'];
            $lists['collections'] = strlen($lists['collections'])>=4 ? '999+' : $lists['collections'];
            //擅长领域
            if (!empty($lists['cate_id'])){
                $lists['cate_id'] = explode(',',$lists['cate_id']);
                foreach ($lists['cate_id'] as $k => $v){
                    $pidTree[] = Categorys::where('id',$v)->first('name');
                }
            }else{
                $pidTree['name'] = [];
            }

            $lists['cate_id'] = $pidTree;

            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 供应商简介页面
     * @param url home.store.storeSummary
     * @param Request $request
     * @return bool
     */
    public function storeSummary(){
        $title = '供应商简介';
        return view('home.store.summary',compact('title'));
    }

    /**
     * 供应商图片页面
     * @param url home.store.storeImg
     * @param Request $request
     * @return bool
     */
    public function storeImg(){
        $title = '供应商图片';
        return view('home.store.image',compact('title'));
    }

    /**
     * 供应商图片
     * @param url home.store.image
     * @param Request $request
     * @param id 供应商id
     * @return bool
     */
    public function imageApi(Request $request){
        try{
            $id = (int)$request->get('id');//供应商id
            if (empty($id)) return $this->writeJson(1,null,'参数错误');
            $lists = Stores::details(['id'=>$id],'image');
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 供应商服务列表页面
     * @param url home.store.storeService
     * @param Request $request
     * @return bool
     */
    public function storeService(){
        $title = '供应商服务列表';
        return view('home.store.service',compact('title'));
    }

    /**
     * 供应商服务
     * @param url home.store.service
     * @param Request $request
     * @param id 供应商id
     * @return bool
     * @return content 简介
     */
    public function serviceApi(Request $request){
        try{
            $id = (int)$request->get('id');//供应商id
            if (empty($id)) return $this->writeJson(1,null,'参数错误');
            $lists = Services::allLists(['store_id'=>$id],['id','store_id','thumb','title','content'], null, 30);
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 供应商服务详情页面
     * @param url home.store.serviceDetails
     * @param Request $request
     * @return bool
     */
    public function serviceDetails(){
        $title = '供应商服务详情';
        return view('home.store.servicedetails',compact('title'));
    }

    /**
     * 供应商服务详情
     * @param url home.store.serviceDetailsApi
     * @param Request $request
     * @param id 服务内容id
     * @return bool
     * @return summary 简介
     */
    public function serviceDetailsApi(Request $request){
        try{
            $id = (int)$request->get('id');//服务内容id
            if (empty($id)) return $this->writeJson(1,route('home.store.servicedetails'),'参数错误');
            $lists = Services::details(['id'=>$id]);
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 供应商案例页面
     * @param url home.store.storeCases
     * @param Request $request
     * @return bool
     */
    public function storeCases(){
        $title = '供应商案例';
        return view('home.store.cases',compact('title'));
    }

    /**
     * 供应商案例
     * @param url home.store.cases
     * @param Request $request
     * @param id 供应商id
     * @param page 页码
     * @return bool
     * @return summary 简介
     */
    public function casesApi(Request $request){
        try{
            $id = (int)$request->get('id');//供应商id
            $page = (int)$request->get('page');//页码
            if (empty($id)) return $this->writeJson(1,null,'参数错误');
            if (empty($page)) return $this->writeJson(1,null,'页码不能为空');
            $lists = Cases::allLists(['store_id'=>$id], ['id','store_id','thumb','title','content'], $page, 10);
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 供应商案例详情页面
     * @param url home.store.casesDetails
     * @param Request $request
     * @return bool
     */
    public function casesDetails(){
        $title = '供应商案例详情';
        return view('home.store.casesdetails',compact('title'));
    }

    /**
     * 供应商案例详情
     * @param url home.store.casesDetailsApi
     * @param Request $request
     * @param id 案例id
     * @return bool
     * @return summary 简介
     */
    public function casesDetailsApi(Request $request){
        try{
            $id = (int)$request->get('id');//案例id
            if (empty($id)) return $this->writeJson(1,route('home.store.casesdetails'),'参数错误');
            $lists = Cases::details(['id'=>$id]);
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 供应商合作商页面
     * @param url home.store.storePartners
     * @param Request $request
     * @return bool
     */
    public function storePartners(){
        $title = '供应商合作';
        return view('home.store.partners',compact('title'));
    }

    /**
     * 供应商合作商
     * @param url home.store.partners
     * @param Request $request
     * @param id 供应商id
     * @return bool
     */
    public function partnersApi(Request $request){
        try{
            $id = (int)$request->get('id');//供应商id
            if (empty($id)) return $this->writeJson(1,null,'参数错误');
            $lists = Stores::details(['id'=>$id],'partners');
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 供应商评价页面
     * @param url home.store.storeEvaluates
     * @param Request $request
     * @return bool
     */
    public function storeEvaluates(){
        $title = '供应商评价';
        return view('home.store.evaluates',compact('title'));
    }

    /**
     * 供应商评价
     * @param url home.store.evaluatesList
     * @param Request $request
     * @param id 供应商id
     * @param type 1:好评 2：中评 3：差评
     * @param page 页码
     * @return bool
     * @return average_star 当前评价的平均星星(星星是几，就是几分)
     * @return avg_good 好评率
     * @return avg_speed 平均工作速度
     * @return avg_quality 平均工作质量
     * @return avg_quality 平均工作态度
     * @return good 好评数
     * @return middle 中评数
     * @return bad 差评数
     */
    public function evaluatesList(Request $request){
        try{
            $id = (int)$request->get('id');//供应商id
            if (empty($id)) return $this->writeJson(1,null,'参数错误');
            $page = (int)$request->get('page');//页码
            if (empty($page)) return $this->writeJson(1,null,'页码不能为空');
            $map = [
                'store_id' => $id,
                'type' => (int)$request->get('type',1),
            ];
            $lists = StoreEvaluates::allLists($map,['*'],$page,3);
            foreach ($lists as $k=>$v){
                $lists[$k]['user_name'] = '**'.mb_substr($v['user_name'],-2,4,"utf-8");
            }
            $sum = StoreEvaluates::counts(['store_id'=>$id]);//总评论数
            $good = StoreEvaluates::counts(['store_id'=>$id,'type'=>1]);//好评数
            $speed = StoreEvaluates::sums(['store_id'=>$id], 'speed');
            $quality = StoreEvaluates::sums(['store_id'=>$id], 'quality');
            $attitude = StoreEvaluates::sums(['store_id'=>$id], 'attitude');
            $store['avg_good'] = empty($sum) ? 100 : intval(round (($good/$sum)*100));//好评率
            $store['avg_speed'] = empty($sum) ? 5 : intval(round ($speed/$sum));//平均工作速度
            $store['avg_quality'] = empty($sum) ? 5 : intval(round ($quality/$sum));//平均工作质量
            $store['avg_attitude'] = empty($sum) ? 5 : intval(round ($attitude/$sum));//平均工作态度

            $middle = StoreEvaluates::counts(['store_id'=>$id,'type'=>2]);//中评数
            $bad = StoreEvaluates::counts(['store_id'=>$id,'type'=>3]);//差评数

            $store['good'] = strlen($good)>=4 ? '999+' : $good;//好评数
            $store['middle'] = strlen($middle)>=4 ? '999+' : $middle;
            $store['bad'] = strlen($bad)>=4 ? '999+' : $bad;

            $evaluate['list'] = $lists;
            $evaluate['store'] = $store;
            return $this->writeJson(0,$evaluate);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 供应商收藏
     * @param url home.store.storeCollectApi
     * @param Request $request
     * @param collect_id 收藏内容id
     * @return bool
     */
    public function storeCollectApi(Request $request){
        try{
            $user_id = auth()->guard('web')->id();
            if (empty($user_id)) return response()->json($data = ["code"=>300,"data"=>null,"msg"=>'请先登录'], $status = 307);
            $userinfo = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['type','status']);
            if (empty($userinfo)){
                return $this->writeJson(1,null,'用户不存在,请联系客服!');
            }else{
                if($userinfo['status'] == 2){
                    return $this->writeJson(1, null,'账户正在审核中，请等待审核!');
                }elseif($userinfo['status'] == 3){
                    return $this->writeJson(1, null,'账号未通过审核，请前往个人中心查看原因并重新提交审核!');
                }elseif ($userinfo['status'] == 4){
                    return $this->writeJson(1, null,'账号已锁定，请前往个人中心查看原因或联系客服!');
                }
                if ($userinfo['type'] != 1) return $this->writeJson(1,null,'供应商不能收藏店铺!');
            }

            $collect_id = (int)$request->post('collect_id');
            if (empty($collect_id)) return $this->writeJson(1,null,'参数错误');
            $collect = Collections::where(['collect_id'=>$collect_id, 'user_id'=>$user_id, 'type'=>4])->value('id');
            if (empty($collect)){
                $params = [
                    'collect_id' => $collect_id,
                    'user_id' => $user_id,
                    'collect_at' => date('Y-m-d H:i:s'),
                    'type' => 4,
                ];
                Collections::create($params);
                Stores::where('id',$collect_id)->increment('collections');
                return $this->writeJson(0, null, '收藏成功');
            }else {
                Collections::where(['collect_id'=>$collect_id, 'user_id'=>$user_id, 'type'=>4])->delete();
                return $this->writeJson(0, null, '取消收藏成功');
            }
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 评价供应商
     * @param url home.store.storeEvaluatesApi
     * @param store_id 店铺id
     * @param content 评价内容
     * @param speed 速度
     * @param quality 质量
     * @param attitude 态度
     * @return bool
     */
    public function storeEvaluatesApi(Request $request){
        try{
            $user_id = auth()->guard('web')->id();
            if (empty($user_id)) return response()->json($data = ["code"=>300,"data"=>null,"msg"=>'请先登录'], $status = 307);
            $userinfo = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','mobile','avatar','type','status']);
            if (empty($userinfo)){
                return $this->writeJson(1,null,'用户不存在,请联系客服!');
            }else{
                if($userinfo['status'] == 2){
                    return $this->writeJson(1, null,'账户正在审核中，请等待审核!');
                }elseif($userinfo['status'] == 3){
                    return $this->writeJson(1, null,'账号未通过审核，请前往个人中心查看原因并重新提交审核!');
                }elseif ($userinfo['status'] == 4){
                    return $this->writeJson(1, null,'账号已锁定，请前往个人中心查看原因或联系客服!');
                }
                if ($userinfo['type'] != 1) return $this->writeJson(1,null,'供应商不能评价供应商!');
            }

            $store_id = (int)$request->post('store_id');
            $gys_user_id = Stores::where('id',$store_id)->where('status','<>',-1)->value('user_id');//当前店铺用户id
            //判断是否购买商品
            $order = Orders::where(['user_id'=>$user_id,'store_id'=>$store_id,'pay_status'=>2])->pluck('id');
            //判断是否投标
            $bid = BidLists::where(['user_id'=>$user_id,'store_id'=>$gys_user_id])->pluck('id');
            //判断是否有拨打电话
            $gys_mobile = Users::where('id',$gys_user_id)->where('status','<>',-1)->value('mobile');
            $phone = Phonemap::where(['anumber'=>$userinfo['mobile'],'bnumber'=>$gys_mobile,'status'=>1])->where('connet_status','<>',0)->pluck('id');
            //判断是否报名活动
            $act_ids = Activitys::where('user_id',$gys_user_id)->where('status','<>',-1)->pluck('id');
            if (!$act_ids->isEmpty()){
                $sign = SignUps::whereIn('activity_id',$act_ids)->where(['user_id'=>$user_id,'pay_state'=>2])->where('status','<>',-1)->pluck('id');
            }
            if ($order->isEmpty() && $bid->isEmpty() && $phone->isEmpty() &&( $act_ids->isEmpty() || $sign->isEmpty())){
                return $this->writeJson(1,null,'亲，与供应商联系或购买相应服务后才可以评价哦!');
            }
            $ret = StoreEvaluates::where(['user_id'=>$user_id,'store_id'=>$store_id])->where('status','<>',-1)->value('id');
            if (!empty($ret)){
                return $this->writeJson(1,null,'您已评价过此供应商，不能再次评价');
            }

            $params = [
                'user_id' => $user_id,
                'user_name' => $userinfo['username'],
                'user_avatar' => $userinfo['avatar'],
                'store_id' => $store_id,
                'content' => (string)$request->post('content'),
                'speed' => (int)$request->post('speed',5),
                'quality' => (int)$request->post('quality',5),
                'attitude' => (int)$request->post('attitude',5),
            ];
            $params['store_name'] = Stores::where('id',$params['store_id'])->value('store_name');
            $params['average_star'] = intval(round(($params['speed']+$params['quality']+$params['attitude'])/3));//平均分
            if($params['average_star'] ==5 || $params['average_star'] == 4){
                $params['type'] = 1;//好评
            }elseif ($params['average_star'] ==3){
                $params['type'] = 2;//中评
            }elseif ($params['average_star'] ==2 || $params['average_star'] == 1){
                $params['type'] = 3;//差评
            }
            StoreEvaluates::create($params);
            Stores::where('id',$params['store_id'])->increment('praise');//评论量加1
            //计算好评率
            $all = StoreEvaluates::where(['store_id'=>$params['store_id']])->where('status','<>',-1)->count();
            $goods = StoreEvaluates::where(['store_id'=>$params['store_id'], 'type'=>1])->where('status','<>',-1)->count();
            $credit = $goods/$all*100;
            Stores::where('id',$params['store_id'])->update(['credit'=>$credit]);
            return $this->writeJson(0, null, '评价成功');
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

}